package me.thomas.ibmmq;

import java.io.IOException;

import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

public class IBMMQConnector {
	/**
	 * 队列管理器的名称
	 */
	private String qManagerName = "QM_TEST";

	/**
	 * 队列管理器
	 */
	private MQQueueManager qMgr;
	/**
	 * 队列名称
	 */
	private String queueName = "MY.QUEUE";
	/**
	 * 队列
	 */
	private MQQueue qQueue;

	/**
	 * mq服务器所在的主机名称
	 */
	private String hostname = "127.0.0.1";
	/**
	 * 服务器连接通道名称
	 */
	private String channelName = "SYSTEM.AUTO.SVRCONN";

	/**
	 * 监听器监听的端口
	 */
	private int port = 1414;
	/**
	 * 传输的编码类型
	 */
	private int CCSID = 1208;

	public void init() throws MQException {
		MQEnvironment.hostname = this.hostname; // 安裝MQ所在的ip address
		MQEnvironment.port = this.port; // TCP/IP port
		MQEnvironment.channel = this.channelName;
		MQEnvironment.CCSID = CCSID;
		qMgr = new MQQueueManager(this.qManagerName);
		int qOptioin = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_INQUIRE | MQC.MQOO_OUTPUT;
		qQueue = qMgr.accessQueue(queueName, qOptioin);
	}

	/**
	 * 发送信息
	 */

	public void SendMsg(byte[] qByte) {
		try {
			MQMessage qMsg = new MQMessage();
			qMsg.write(qByte);
			MQPutMessageOptions pmo = new MQPutMessageOptions();
			qQueue.put(qMsg, pmo);
			System.out.println("The message is sent!");
			System.out.println("\tThe message is " + new String(qByte, "GBK"));
		} catch (MQException e) {
			e.printStackTrace();
			System.out.println("A WebSphere MQ error occurred : Completion code " + e.completionCode
					+ " Reason Code is " + e.reasonCode);
		} catch (java.io.IOException e) {
			e.printStackTrace();
			System.out.println("An error occurred whilst to the message buffer " + e);
		}

	}

	/**
	 * 从消息队列取数据
	 * @throws Exception 
	 */
	public void GetMsg() throws Exception {
			MQMessage retrievedMessage = new MQMessage();

			MQGetMessageOptions gmo = new MQGetMessageOptions();
			gmo.options += MQC.MQPMO_SYNCPOINT;
			qQueue.get(retrievedMessage, gmo);
			int length = retrievedMessage.getDataLength();

			byte[] msg = new byte[length];

			retrievedMessage.readFully(msg);

			String sMsg = new String(msg, "GBK");

	}

	/**
	 * 释放资源
	 */
	public void release() {
		try {
			if (null != qQueue)
				qQueue.close();
			if (null != qMgr)
				qMgr.disconnect();
		} catch (MQException e) {
			System.out.println("A WebSphere MQ error occurred : Completion code " + e.completionCode
					+ " Reason Code is " + e.reasonCode);
		}
	}
}
